package cn.maihe.elg.operation.common.validator;

import cn.maihe.elg.operation.common.annotation.NumberFmt;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Description
 * @Author WJH
 * @Date 2021/07/13
 */
@Slf4j
public class NumberFmtValidator implements ConstraintValidator<NumberFmt, String> {

    private int scale;
    private double min;
    private double max;

    @Override
    public void initialize(NumberFmt constraintAnnotation) {
        this.scale = constraintAnnotation.scale();
        this.min = constraintAnnotation.min();
        this.max = constraintAnnotation.max();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        boolean valid = false;
        if (StringUtils.isNotBlank(value)) {
            try {
                double curVal = Double.valueOf(value);
                if (Double.compare(curVal, min) >= 0 && Double.compare(max, curVal) >= 0) {
                    //如果包含小数点，则必须要在上送保留的小数点位数
                    if (value.contains(".")) {
                        int curScale = value.substring(value.indexOf(".") + 1).length();
                        if (curScale <= scale) {
                            valid = true;
                        }
                    } else {
                        valid = true;
                    }
                }
            } catch (Exception e) {
                valid = false;
            }
        } else {
            valid = true;
        }
        return valid;
    }

    public static void main(String[] args) {
        try {
            String a = "yyyy-MM-dd HH:mm:ss";
            String v = "1976-01-12 12:12:12";
            LocalDateTime.parse(v, DateTimeFormatter.ofPattern(a));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
